<template>
  <div class="register-container">
    <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">用户注册</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="registerForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="registerForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="on"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="confirmPasswordType"
          ref="confirmPassword"
          v-model="registerForm.confirmPassword"
          :type="confirmPasswordType"
          placeholder="请确认密码"
          name="confirmPassword"
          tabindex="3"
          auto-complete="on"
        />
        <span class="show-pwd" @click="showConfirmPwd">
          <svg-icon :icon-class="confirmPasswordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-form-item prop="gender">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <div class="gender-label">性别：</div>
        <el-radio-group v-model="registerForm.gender" class="gender-group" tabindex="4" aria-label="性别选择" @keyup.enter.native="handleRegister">
          <el-radio label="male">男</el-radio>
          <el-radio label="female">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item prop="email">
        <span class="svg-container">
          <svg-icon icon-class="email" />
        </span>
        <el-input
          ref="email"
          v-model="registerForm.email"
          placeholder="请输入邮箱"
          name="email"
          type="email"
          tabindex="5"
          auto-complete="on"
        />
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:20px;" tabindex="6" @click.native.prevent="handleRegister">注册</el-button>

      <div class="tips">
        <span>已有账号？</span>
        <el-button type="text" @click="goToLogin">立即登录</el-button>
      </div>

    </el-form>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import { register } from '@/api/user'

export default {
  name: 'Register',
  data() {
    // 用户名校验规则
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }

    // 密码校验规则
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度至少为6位'))
      } else {
        callback()
      }
    }

    // 确认密码校验规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    // 邮箱校验规则
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(value)) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }

    // 性别校验规则
    const validateGender = (rule, value, callback) => {
      if (!value || value === '') {
        callback(new Error('请选择性别'))
      } else {
        callback()
      }
    }

    // 数据模型
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        gender: ''
      },
      registerRules: {
        username: [
          { required: true, trigger: 'blur', validator: validateUsername }
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePassword }
        ],
        confirmPassword: [
          { required: true, trigger: 'blur', validator: validateConfirmPassword }
        ],
        email: [
          { required: true, trigger: 'blur', validator: validateEmail }
        ],
        gender: [
          { required: true, trigger: 'change', validator: validateGender }
        ]
      },
      loading: false,
      passwordType: 'password',
      confirmPasswordType: 'password'
    }
  },

  methods: {
    // 展示密码
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },

    // 展示确认密码
    showConfirmPwd() {
      if (this.confirmPasswordType === 'password') {
        this.confirmPasswordType = ''
      } else {
        this.confirmPasswordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.confirmPassword.focus()
      })
    },

    // 注册方法
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true

          // 准备注册数据，移除确认密码字段
          const registerData = {
            username: this.registerForm.username,
            password: this.registerForm.password,
            email: this.registerForm.email,
            gender: this.registerForm.gender === 'male' ? 1 : 0
          }

          // 调用注册后端接口
          register(registerData).then((result) => {
            console.log(result)
            if (result.data.code === 1) {
              this.$message.success('注册成功！')
              this.$router.push('/login')
              this.resetForm()
            } else {
              this.$message.error(result.data.msg || '注册失败')
              this.loading = false
            }
          }).catch(error => {
            console.error('注册失败:', error)
            this.$message.error('注册失败，请稍后重试')
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 跳转到登录页面
    goToLogin() {
      this.$router.push('/login')
    },

    // 重置表单
    resetForm() {
      this.$refs.registerForm.resetFields()
      this.registerForm = {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        gender: ''
      }
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .register-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.register-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }

  .gender-group {
    display: inline-block;
    width: 85%;
    margin-left: 30px;
    padding: 12px 0;

    .el-radio {
      color: $light_gray;
      margin-right: 20px;
      margin-bottom: 5px;

      .el-radio__label {
        color: $light_gray;
        font-size: 14px;
      }

      .el-radio__input.is-checked .el-radio__inner {
        border-color: #409EFF;
        background: #409EFF;
      }

      .el-radio__input.is-checked + .el-radio__label {
        color: #409EFF;
      }

      &:hover .el-radio__label {
        color: #409EFF;
      }

      .el-radio__input:focus + .el-radio__label {
        color: #409EFF;
      }
    }
  }

  .gender-label {
    display: inline-block;
    color: $light_gray;
    font-size: 14px;
    margin-left: 30px;
    margin-bottom: 8px;
  }

  @media (max-width: 768px) {
    .gender-group {
      width: 80%;
      margin-left: 25px;
      padding: 10px 0;

      .el-radio {
        margin-right: 15px;
        margin-bottom: 8px;

        .el-radio__label {
          font-size: 13px;
        }
      }
    }

    .gender-label {
      margin-left: 25px;
      font-size: 13px;
    }
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.register-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .register-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    text-align: center;

    span {
      margin-right: 10px;
    }

    .el-button {
      color: #409EFF;
      padding: 0;
      font-size: 14px;
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
      font-family: '楷体';
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
